package com.charles.seckillPlatform.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.charles.seckillData.domain.SysGood;
import com.charles.seckillData.domain.SysOrder;
import com.charles.seckillComponentCommon.constants.CacheConstants;
import com.charles.seckillComponentCommon.exceptions.ServiceException;
import com.charles.seckillComponentRedis.service.RedisService;
import com.charles.seckillPlatform.mapper.SysGoodMapper;
import com.charles.seckillPlatform.service.AlipayOrderService;
import com.charles.seckillPlatform.service.SysOrderService;
import com.charles.seckillPlatform.vo.OrderPayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * @author Charles-H
 * <p>
 * 支付宝控制层
 */
@RestController
@RequestMapping("/alipay")
@CrossOrigin // 上线需要指定具体的 origins
public class AliPayController {

    @Autowired
    private AlipayOrderService alipayOrderService;

    @Autowired
    private SysGoodMapper sysGoodMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysOrderService sysOrderService;


    /**
     * 返回AliPay支付页面
     */
    @PostMapping("/payOrder/{orderId}")
    public String payOrder(@PathVariable("orderId") String orderId) throws AlipayApiException {
        OrderPayVo orderVo = new OrderPayVo();
        SysOrder order = redisService.getCacheObject(CacheConstants.ORDER_ID + orderId);

        // 订单状态 2: 已过期
        if (order == null || order.getStatus().equals("2")) {
            throw new ServiceException("您的订单已过期。");
        }

        // 订单状态 1: 已支付
        if (order.getStatus().equals("1")) {
            throw new ServiceException("您的订单已完成支付。");
        }

        SysGood good = sysGoodMapper.getGood(order.getGood_id());
        orderVo.setOut_trade_no(order.getOrder_id());
        orderVo.setSubject(order.getGood_title());
        orderVo.setTotal_amount(Optional.ofNullable(order.getSeckill_price()).orElse(order.getPrice()).toString());
        orderVo.setBody(good.getGood_desc());
        return alipayOrderService.payOrder(orderVo);
    }

    /**
     * Alipay 支付响应
     */
    @PostMapping("/payOrder/callback")
    public String handleAlipayNotify(@RequestBody Map<String, String> params) {
        try {
            String charset = "UTF-8";
            String aliPayPublicKey = "your_alipay_public_key";
            
            boolean signVerify = AlipaySignature.rsaCertCheckV1(params, aliPayPublicKey, charset, "RSA2");
            
            if (signVerify) {
                String tradeStatus = params.get("trade_status");
                
                // 这里暂时只处理订单支付成功阶段
                if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
                    String orderId = params.get("out_trade_no");
                    sysOrderService.payOrderSuccess(orderId, "2");
                }
                
            } else {
                return "fail";
            }
            
        } catch (Exception e) {
            return "fail";
        }
        return "success";
    }

}
